package com.kitty.mybatis.mybatisv1.executor;

import com.kitty.mybatis.mybatisv1.mapping.KittyBoundSql;
import com.kitty.mybatis.mybatisv1.mapping.KittyMappedStatement;
import com.kitty.mybatis.mybatisv1.session.KittyConfiguration;
import com.kitty.mybatis.mybatisv1.executor.statement.KittyStatementHandler;
import sun.rmi.runtime.Log;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * @Description
 * @Author SHEN
 * @Date 2020/11/1
 */
public class KittySimpleExecutor extends KittyBaseExecutor {


    protected KittySimpleExecutor(KittyConfiguration configuration) {
        super(configuration);
    }

    @Override
    protected <E> List<E> doQuery(KittyMappedStatement ms, Object parameter, KittyBoundSql boundSql) throws SQLException {
        Statement stmt = null;
        try {
            KittyConfiguration configuration = ms.getConfiguration();
            //新建一个StatementHandler
            //这里看到ResultHandler传入了
            KittyStatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, boundSql);
            //准备语句
            stmt = prepareStatement(handler);
            //StatementHandler.query
            return handler.<E>query(stmt);
        } finally {
            closeStatement(stmt);
        }
    }

    protected void closeStatement(Statement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
            }
        }
    }

    private Statement prepareStatement(KittyStatementHandler handler) throws SQLException {
        Statement stmt;
        Connection connection = getConnection(null);
        //调用StatementHandler.prepare
        stmt = handler.prepare(connection);
        //调用StatementHandler.parameterize
        handler.parameterize(stmt);
        return stmt;
    }

    protected Connection getConnection(Log statementLog) throws SQLException {
        //todo
        return null;
    }
}
